import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { HttpClient, HttpRequest, HttpResponse, HttpEvent } from '@angular/common/http';
import { UploadChangeParam, UploadFile } from 'ng-zorro-antd/upload';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-operamodal',
    templateUrl: './operaModal.component.html',
    styleUrls: ['./cadDrawings.component.less']
})
export class OperaModalComponent implements OnInit {
    @Input() operaWidth: any;
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() cadData: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Input() operaText: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    delData: any = { 'count': 0, 'id': [] };
    xbSelect = [];
    czSelect = [];
    uploadUrl = environment.project + '/file/uploadBatch';
    upladDel = environment.project + '/file/delete';
    fileList = [];

    compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.id === o2.id : o1 === o2);
    customReq = (item) => {
        const formData = new FormData();
        formData.append('dir', 'CAD');
        formData.append('file', item.file);

        const req = new HttpRequest('POST', item.action!, formData, {
            reportProgress: false,
            withCredentials: true
        });
        return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
            if (event instanceof HttpResponse) {
                // 处理成功
                item.onSuccess!(event.body, item.file!, event);
            }
        });
    }

    constructor(
        private msg: NzMessageService,
        private http: HttpClient
    ) { }

    ngOnInit() {
        if (!this.operaWidth) {
            this.operaWidth = '500';
        }
        switch (this.operaType) {
            case 'add':
                this.getApi(() => {
                    // to do
                });
                break;
            case 'edit':
                let editStatus = false;
                let editCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        editCount += 1;
                        this.objData = item;
                        editStatus = true;
                    }
                }
                if (editStatus && editCount === 1) {
                    if (this.objData.cadFiles) {
                        for (let i = 0; i < this.objData.cadFiles.length; i++) {
                            this.fileList.push({
                                uid: JSON.stringify(i + 1),
                                name: this.objData.cadFiles[i].fileName,
                                url: this.objData.cadFiles[i].fileUrl
                            });
                        }
                    }
                    this.getApi(() => {
                        // 回填数据
                        this.operaData.id = this.objData.id;
                        for (const item of this.xbSelect) {
                            if (item.name === this.objData.line) {
                                this.operaData.line = { 'id': item.id, 'name': this.objData.line };
                                break;
                            }
                        }
                        this.lbChange(this.operaData.line, () => {
                            this.operaData.stationId = { 'id': this.objData.stationId, 'name': this.objData.stationName };
                        });
                        for (const item of this.cadData.tcmcSelect) {
                            if (item.label === this.objData.album) {
                                this.operaData.albumId = item.value;
                                break;
                            }
                        }
                        for (const item of this.cadData.tzmcSelect) {
                            if (item.label === this.objData.dwg) {
                                this.operaData.dwgId = item.value;
                                break;
                            }
                        }
                        this.operaData.remark = this.objData.remark;
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'del':
                let delStatus = false;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        this.delData.count++;
                        this.delData.id.push(item.id)
                        delStatus = true;
                    }
                }
                if (delStatus) {
                    this.getApi(() => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择数据删除');
                }
                break;
        }
    }
    getApi(callback) {
        setTimeout(() => {
            this.Visible = true;
            const allApi = [
                this.http.get(environment.project + '/getAllLine')
            ];
            forkJoin(allApi).subscribe((results: any) => {
                if (!results[0].code) {
                    this.xbSelect = results[0].data;
                }
                callback();
            });
        }, 200);
    }
    handleChange(info: UploadChangeParam) {
        switch (info.file.status) {
            case 'done':
                const response = info.file.response;
                if (response) {
                    if (!response.code) {
                        for (const item of response.data) {
                            this.fileList.push({
                                name: item.fileName,
                                url: item.fileUrl
                            });
                        }
                    } else {
                        this.msg.error(response.msg);
                    }
                }
                break;
            case 'removed':
                const fileUrl = new FormData();
                fileUrl.append('url', info.file.url);
                this.http.post(this.upladDel, fileUrl).subscribe((res: any) => {
                    if (!res.code) {
                        this.msg.success('删除成功');
                        for (let i = 0; i < this.fileList.length; i++) {
                            if (this.fileList[i].url === info.file.url) {
                                this.fileList.splice(i, 1);
                                break;
                            }
                        }
                    } else {
                        this.msg.error(res.msg);
                    }
                });
                break;
            case 'error':
                this.msg.error(`${info.file.name} 上传失败`);
                break;
        }
    }
    lbChange(e, callback?) {
        if (e) {
            this.czSelect = [];
            this.http.get(environment.project + '/getStationByLine?line=' + e.id).subscribe((res: any) => {
                if (!res.code) {
                    this.czSelect = res.data;
                    if (callback) {
                        callback();
                    }
                }
            });
        }
    }
    Ok() {
        let param: any = {};
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.line || !this.operaData.stationId || !this.fileList.length ||
                    this.operaData.albumId === undefined || this.operaData.albumId === '' ||
                    this.operaData.dwgId === undefined || this.operaData.dwgId === ''
                ) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                param = {
                    'line': this.operaData.line.name,
                    'stationId': this.operaData.stationId.id,
                    'stationName': this.operaData.stationId.name,
                    'album': this.operaData.albumId,
                    'dwg': this.operaData.dwgId,
                    'cadFiles': this.fileList,
                    'remark': this.operaData.remark
                }
                const paramTemp: any = [];
                for (const item of param.cadFiles) {
                    paramTemp.push({
                        fileName: item.name,
                        fileUrl: item.url
                    });
                }
                param.cadFiles = paramTemp;
                if (this.operaType === 'edit') {
                    param.id = this.operaData.id;
                }
                break;
            case 'del':
                param = this.delData.id;
                break;
        } 
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                this.msg.error('操作失败');
            }
        });
    }

    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}